package com.lonely.fx;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @date: 2022-07-19 14:19
 * @author: ztkj-hzb
 * @description: 圆形进度条
 **/
public class ProgressIndicatorSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox hBox = new HBox();
        hBox.setAlignment(Pos.CENTER);

        //创建进度条
        ProgressIndicator progressIndicator = new ProgressIndicator();

        //设置宽高
        //progressIndicator.setPrefWidth(100);
        //progressIndicator.setPrefHeight(100);

        //设置进度---当没有设置进度，或者进度为负数时，样式是一直转的
        //progressIndicator.setProgress(0.5);
        //progressIndicator.setProgress(ProgressIndicator.INDETERMINATE_PROGRESS);

        //当存在进度的时候返回false，没有进度的以动画方式的时候为true
        //System.out.println(progressIndicator.isIndeterminate());

        //案例，动态进度条
        ProgressIndicatorTask progressIndicatorTask = new ProgressIndicatorTask();
        progressIndicatorTask.setDelay(Duration.millis(1000));
        progressIndicatorTask.setPeriod(Duration.millis(100));
        progressIndicatorTask.start();

        progressIndicatorTask.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) {
                return;
            }

            if (newValue > 1) {
                progressIndicatorTask.cancel();
            }

            progressIndicator.setProgress(newValue);

        });


        hBox.getChildren().addAll(progressIndicator);
        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();
    }


    private class ProgressIndicatorTask extends ScheduledService<Double> {

        private double size = 0.0;

        /**
         *
         */
        @Override
        protected Task<Double> createTask() {
            return new Task<Double>() {
                @Override
                protected Double call() throws Exception {
                    return size += 0.1;
                }
            };
        }
    }
}
